package com.zlc.platform.controller;

import com.zlc.common.util.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Slf4j
@Api(tags = "文件操作相关")
@RestController
@RequestMapping("/api/file")
public class FileController {

    @ApiOperation(value = "上传文件")
    @PostMapping(value = "/uploadFile")
    public String uploadFile(MultipartFile file) throws IOException {
        log.info("开始上传文件");
//        String path = File.separator + "home" + File.separator + "data" + File.separator + "file";
        String path = "/home/data/file";
        return FileUtil.upload(path, file.getOriginalFilename(), file.getInputStream());
    }

    @ApiOperation(value = "下载文件")
    @GetMapping(value = "/download")
    public void download(@RequestParam(value = "path") String filePath, HttpServletResponse response){
        File file = new File(filePath);
        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + file.getName() + "\"");
        response.setContentLength((int) file.length());

        // 写入文件内容到响应流
        try (FileInputStream fis = new FileInputStream(file);
             ServletOutputStream sos = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                sos.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
